import sys
import mdp
import loadData_David
import matplotlib.pyplot as mpl


def main(filename):
    # load data from file
    try:
        #NOTE: The SVM performanace degrades (even on training data) when normalize=True
        mats = loadData_David.load(filename, rseed=-1, normalize=False, transpose=False)
        trainingMat = mats[0]
        testingMat = mats[1]
        
        trainingDiscreteMat = mats[2]
        testingDiscreteMat= mats[3]

        print('Data loaded')
    except Exception as e:
        print(e)
        exit(1)

    from sklearn import svm
    clf = svm.SVC()
    
    #Train the algorithm (i.e. machine learning, compute support vectors)
    trainSVM(clf, trainingMat, trainingDiscreteMat, stdout=False)
    
    testSVM(clf, trainingMat, trainingDiscreteMat, stdout=False)
        
    #TESTING MATRIX
    print('##### TESTING MATRIX #####')
    testSVM(clf, testingMat, testingDiscreteMat, stdout=False)


# Train the SVM with Case/Control data and a Y array of discrete Case/Control values (i.e. known values)
def trainSVM(clf, trainingMat, trainingDiscreteMat, stdout=False):
    #Create a Y array to help train the SVM (Y contains 1 for 'Case', 0 for 'Control')
    Y = range(0,len(trainingMat))
    for i in range(0,len(trainingMat)):
        if trainingDiscreteMat[i,1]=='Control':
            Y[i] = 0
        else:
            Y[i] = 1

    logging = clf.fit(trainingMat, Y)
    if(stdout):
        print(logging)

# Test the SVM against data with known Case/Control values and compute accuracy
def testSVM(clf, testingMat, testingDiscreteMat, stdout=False):
    #Create a Y array to help train the SVM (Y contains 1 for 'Case', 0 for 'Control')
    Y = range(0,len(testingMat))
    for i in range(0,len(testingMat)):
        if testingDiscreteMat[i,1]=='Control':
            Y[i] = 0
        else:
            Y[i] = 1
        
    numCorrect = 0
    for i in range(0,len(testingMat)):
        if(stdout):
            print('testingDiscreteMat[{}]: {}; Y: {}; prediction: {}'.format(i, testingDiscreteMat[i], Y[i], clf.predict(testingMat[i])))
        if clf.predict(testingMat[i])[0] == Y[i]:
            numCorrect = numCorrect + 1
    print('numCorrect: {}  (out of {})'.format(numCorrect, len(testingMat)))


# display the proper command usage and exit
def commandFormat():
    print('python analyze.py <path_to_data>')
    exit(1)
    
if __name__=='__main__':
    # check for valid arguments
    if len(sys.argv)<2:
        commandFormat()
    # run analysis on given file
    main(sys.argv[1])
